﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace _25_3_29
{
    public partial class Form2 : Form
    {
        Order order;
        OrderDetails details;
        OrderService _service;
   
        string constring = "data source=localhost;database=dingdan;user id=root;password=asdfg123456;pooling=true;charset=utf8;";
        MySqlConnection msc;
        public Form2(OrderService orderservice)
        {
            InitializeComponent();
            order = new Order();
            details = new OrderDetails();
            _service = orderservice;
            msc= new MySqlConnection(constring);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }


        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBox1.Text))
            {
                return; // 如果为空则不处理
            }

            if (int.TryParse(textBox1.Text, out int id))
            {
                order.OrderId = id;
            }
            else
            {
                MessageBox.Show("请输入有效的数字作为订单ID");
                textBox1.Text = ""; // 清空无效输入
                textBox1.Focus();
            }
        }
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBox2.Text))
            {
                return; // 如果为空则不处理
            }

            // 检查输入是否有效
            if (IsValidCustomerName(textBox2.Text))
            {
                order.Customer = textBox2.Text;
            }
            else
            {
                MessageBox.Show("请输入有效的客户名称（不能为空或纯数字）");
                textBox2.Text = ""; // 清空无效输入
                textBox2.Focus();
            }
        }

        private bool IsValidCustomerName(string name)
        {
            // 1. 不能为空或纯空格
            if (string.IsNullOrWhiteSpace(name))
                return false;

            // 2. 不能是纯数字
            if (name.All(char.IsDigit))
                return false;

            // 3. 不能包含特殊字符等
            if (name.Any(c => !char.IsLetterOrDigit(c) && !char.IsWhiteSpace(c)))
                return false;

            return true;
        }
        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            //if (string.IsNullOrWhiteSpace(textBox5.Text))
            //{
            //    return; // 空输入不处理(import!!! 防止清空时更新，虽然通过调换顺序实现了，但是保险起见
            //}
            //其实不然 因为最后清空了，所以这个代码不能要，要不然报失效
            details.ProductName = textBox3.Text;
            //Console.WriteLine($"输入内容: {textBox3.Text}"); // 调试输出
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {


            if (string.IsNullOrWhiteSpace(textBox4.Text))
            {
                return; // 空输入不处理
            }

            if (decimal.TryParse(textBox4.Text, out decimal quantity) && quantity > 0)
            {
                details.Quantity = quantity;
            }
            else
            {
                MessageBox.Show("请输入有效的数量（必须为正数）");
                textBox4.Text = ""; 
                textBox4.Focus();   
            }
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {

            if (string.IsNullOrWhiteSpace(textBox5.Text))
            {
                return; // 空输入不处理
            }

            if (decimal.TryParse(textBox5.Text, out decimal price) && price > 0)
            {
                details.Price = price;
            }
            else
            {
                MessageBox.Show("请输入有效的价格（必须为正数）");
                textBox5.Text = ""; // 清空无效输入
                textBox5.Focus();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // 1. 检查 order 和 details 是否已初始化
            if (order == null)
            {
                MessageBox.Show("订单未初始化，请先创建订单");
                return;
            }

            if (details == null || string.IsNullOrEmpty(details.ProductName))
            {
                MessageBox.Show("请输入有效的商品信息");
                textBox3.Focus(); 
                return;
            }

            if (details.Quantity <= 0)
            {
                MessageBox.Show("数量必须大于0");
                textBox4.Focus();
                return;
            }

            // 3. 检查价格是否有效（>0）
            if (details.Price <= 0)
            {
                MessageBox.Show("价格必须大于0");
                textBox5.Focus();
                return;
            }

            // 4. 添加到订单明细列表
            order.Details.Add(details);

            // 5. 清空输入框并重置 details 对象
            details = new OrderDetails();
            textBox3.Clear();
            textBox4.Clear();
            textBox5.Clear();
            


            label7.Text = "添加成功";
            label7.Visible = true;
            textBox3.Focus();
        }

        private void button3_Click(object sender, EventArgs e) // 完成按钮
        {
            if (order == null || order.Details == null || !order.Details.Any())
            {
                MessageBox.Show("订单信息不完整，请添加商品后再提交！", "提示",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                _service.AddOrder(order);
                
                SaveOrderToDatabase(order);

                MessageBox.Show("订单创建成功！", "成功",
                              MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.Close(); // 关闭当前窗体
            }
            catch (InvalidOperationException ex)  // 捕获重复ID异常
            {
                MessageBox.Show(ex.Message, "操作失败",
                              MessageBoxButtons.OK, MessageBoxIcon.Error);
                textBox1.Focus();  // 聚焦到订单ID输入框
            }

        }

        private void button2_Click(object sender, EventArgs e) // 取消按钮
        {
            var result = MessageBox.Show("确定要取消当前订单吗？", "确认",
                                       MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                order = null;
                details = null;
                this.Close();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            MessageBox.Show(order.ToString());
        }

        private void SaveOrderToDatabase(Order order)
        {
            try
            {
                msc.Open();

                // 开始事务
                using (MySqlTransaction transaction = msc.BeginTransaction())
                {
                    try
                    {
                        // 1. 保存订单主表
                        string orderSql = @"INSERT INTO orders 
                                         (order_id, customer,detailsSummary,totalAmount) 
                                         VALUES (@id, @customer,@details,@total)";

                        using (MySqlCommand cmd = new MySqlCommand(orderSql, msc, transaction))
                        {
                            cmd.Parameters.AddWithValue("@id", order.OrderId);
                            cmd.Parameters.AddWithValue("@customer", order.Customer);
                            cmd.Parameters.AddWithValue("@details", order.DetailsSummary);
                            cmd.Parameters.AddWithValue("@total", order.TotalAmount);
                            cmd.ExecuteNonQuery();
                        }

                        // 2. 保存订单明细
                        string detailSql = @"INSERT INTO order_details 
                                           (order_id, product_name, quantity, price) 
                                           VALUES (@orderId, @product, @quantity, @price)";

                        foreach (var detail in order.Details)
                        {
                            using (MySqlCommand cmd = new MySqlCommand(detailSql, msc, transaction))
                            {
                                cmd.Parameters.AddWithValue("@orderId", order.OrderId);
                                cmd.Parameters.AddWithValue("@product", detail.ProductName);
                                cmd.Parameters.AddWithValue("@quantity", detail.Quantity);
                                cmd.Parameters.AddWithValue("@price", detail.Price);
                                cmd.ExecuteNonQuery();
                            }
                        }

                        // 提交事务
                        transaction.Commit();
                    }
                    catch
                    {
                        // 回滚事务
                        transaction.Rollback();
                        throw;
                    }
                }
            }
            finally
            {
                if (msc.State == System.Data.ConnectionState.Open)
                {
                    msc.Close();
                }
            }
        }

    }


}
